<template>
  <div>
    <ContentHeader title="修改密码" />
    <ContentBody>
      <div style="width:100%;background:#fff;padding:20px;">
        <el-form
          :model="form" :rules="rules"
          style="width:450px;"
          ref="refPasswordForm"
          label-width="120px"
          label-position="right"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input type="password" v-model="form.oldPassword" placeholder="请填写旧密码" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="form.newPassword" placeholder="请填写新密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="retryPassword">
            <el-input type="password" v-model="form.retryPassword" placeholder="请确认密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdate">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </ContentBody>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus'

const store = useUserStore()
const form = reactive({
  oldPassword: '',
  newPassword: '',
  retryPassword: ''
})
const rules = {
  oldPassword: [
    {required: true, message: '请填写旧密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请填写新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur'}
  ],
  retryPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {validator: (rule : any, value : string, callback : any) => {
      if (value != form.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }, trigger: 'blur'}
  ]
}
const refPasswordForm = ref()

function handleUpdate() {
    refPasswordForm.value.validate(async (valid : boolean) => {
      if (valid) {
        const res = await store.updatePassword({
            newPassword: form.newPassword,
            oldPassword: form.oldPassword,
            confirmPassword: form.retryPassword
        })
        if (res) {
          ElMessage.success('修改成功')
        }
      }
    })
}
</script>